// ==UserScript==
// @name         京东店铺执照查看
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  在非自营京东店铺页面添加执照查看按钮，悬停显示链接
// @author       楚子风
// @match        https://item.jd.com/*
// @match        https://mall.jd.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=jd.com
// @scriptUrl    https://gitee.com/chuzifeng/script-cat-script/raw/master/京东-店铺执照查看.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 检查页面title是否包含"自营"
    if (document.title.includes('自营')) {
        return;
    }

    // 等待pageConfig对象出现的辅助函数
    function waitForPageConfig(maxAttempts = 20, interval = 500) {
        return new Promise((resolve, reject) => {
            let attempts = 0;

            const check = () => {
                attempts++;
                if (typeof window.pageConfig !== 'undefined') {
                    console.log('检测到pageConfig对象');
                    resolve(window.pageConfig);
                } else if (attempts >= maxAttempts) {
                    reject(new Error('等待超时，未找到pageConfig对象'));
                } else {
                    setTimeout(check, interval);
                }
            };

            // 立即检查一次
            if (typeof window.pageConfig !== 'undefined') {
                resolve(window.pageConfig);
            } else {
                console.log('等待pageConfig对象加载...');
                setTimeout(check, interval);
            }
        });
    }

    // 主逻辑
    async function main() {
        let shopId = null;

        // 商品页面逻辑
        if (window.location.href.includes('item.jd.com')) {
            try {
                const pageConfig = await waitForPageConfig();

                // 检查product对象和shopId是否存在
                if (pageConfig.product && pageConfig.product.shopId) {
                    shopId = pageConfig.product.shopId;
                    console.log('从pageConfig.product中获取到店铺ID:', shopId);
                } else {
                    console.log('pageConfig.product中不存在shopId属性');
                }
            } catch (error) {
                console.log('获取pageConfig时出错:', error.message);
            }
        }
        // 店铺页面逻辑
        else {
            const xpathExpression = '//input[@id="shop_id"]';
            const result = document.evaluate(xpathExpression, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            const shopIdElement = result.singleNodeValue;

            if (shopIdElement && shopIdElement.value) {
                shopId = shopIdElement.value.trim();
                console.log('从input元素中获取到店铺ID:', shopId);
            } else {
                console.log('店铺页面未找到input#shop_id元素');
            }
        }

        // 验证shopId是否存在且格式正确
        if (!shopId || !/^\d+$/.test(shopId)) {
            console.log('未找到有效的店铺ID或格式不正确');
            return;
        }

        const licenceUrl = `https://mall.jd.com/showLicence-${shopId}.html`;

        // 创建悬浮按钮
        const button = document.createElement('button');
        button.textContent = '查看店铺执照';
        button.style.position = 'fixed';
        button.style.top = '60px';
        button.style.left = '10px';
        button.style.zIndex = '9999';
        button.style.width = '120px';
        button.style.height = '30px';
        button.style.padding = '0';
        button.style.backgroundColor = '#e4393c';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.borderRadius = '4px';
        button.style.cursor = 'pointer';
        button.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
        button.style.textAlign = 'center';
        button.style.lineHeight = '30px';

        // 创建链接提示元素
        const tooltip = document.createElement('div');
        tooltip.textContent = licenceUrl;
        tooltip.style.position = 'fixed';
        tooltip.style.display = 'none';
        tooltip.style.top = '95px';
        tooltip.style.left = '10px';
        tooltip.style.zIndex = '10000';
        tooltip.style.maxWidth = '300px';
        tooltip.style.padding = '5px 10px';
        tooltip.style.backgroundColor = '#333';
        tooltip.style.color = 'white';
        tooltip.style.fontSize = '12px';
        tooltip.style.borderRadius = '4px';
        tooltip.style.boxShadow = '0 2px 5px rgba(0,0,0,0.3)';
        tooltip.style.wordBreak = 'break-all';
        tooltip.style.whiteSpace = 'pre-wrap';

        // 添加到页面
        document.body.appendChild(tooltip);
        document.body.appendChild(button);

        let showTimer;

        // 添加按钮鼠标事件
        button.addEventListener('mouseenter', () => {
            showTimer = setTimeout(() => {
                tooltip.style.display = 'block';
            }, 2000);
        });

        button.addEventListener('mouseleave', () => {
            clearTimeout(showTimer);
            tooltip.style.display = 'none';
        });

        tooltip.addEventListener('mouseenter', () => {
            clearTimeout(showTimer);
        });

        tooltip.addEventListener('mouseleave', () => {
            tooltip.style.display = 'none';
        });

        // 添加按钮点击事件
        button.addEventListener('click', () => {
            window.open(licenceUrl, '_blank');
        });
    }

    // 在页面加载完成后执行主逻辑
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        main();
    } else {
        document.addEventListener('DOMContentLoaded', main);
    }
})();